<template>
  <div class="container">
    <el-row class="mb10">
      <el-col :span="16">
        <div class="flex">
          <el-input clearable v-model="data.searchParams.teamName" placeholder="团队名称"
            style="width: 120px; margin-right: 15px">
          </el-input>

          <div class="conUnitName">
            <el-cascader @change="changeUnit" popper-class="gy-cascader" :options="data.orgAllList"
              :props="data.popupTreeProps" v-model="data.searchParams.recommendUnit" :show-all-levels="false"
              placeholder="请选择推荐单位" clearable>

              <template #default="{ data }">
                <el-tooltip :disabled="data.name.length < 13" class="item" effect="dark" :content="data.name"
                  placement="bottom-start">
                  <span>{{ data.name }}</span>
                </el-tooltip>
              </template>
            </el-cascader>
          </div>
          <el-button class="ordinary" @click="search">搜索</el-button>
        </div>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="ordinary" @click="getExport()" v-limit="'KJSL:KJJL:YXKJTD:EXPERT'"> 批量导出 </el-button>
        <el-button type="danger" @click="deleteList" v-limit="'KJSL:KJJL:YXKJTD:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="add" v-limit="'KJSL:KJJL:YXKJTD:REWARDS'">申报奖励</el-button>
      </el-col>
    </el-row>
    <div>
      <Table :loading="data.isLoading" :tableArr="data.allTableData" :pagination="data.page" :columns="data.columns"
        :total="data.page.total" @delectTable="delectIds" @currentChange="currentChange">
        <template #operate="{ row }">
          <div v-if="row.status == '待提交'">
            <el-button size="small" class="ordinary" @click="handleEdit(row)"
              v-limit="'KJSL:KJJL:YXKJTD:EDIT'">编辑</el-button>
            <el-button size="small" class="ordinary" @click="handletj(row)"
              v-limit="'KJSL:KJJL:YXKJTD:SUBMIT'">提交</el-button>
          </div>
          <div v-if="row.status == '办理中'">
            <el-button size="small" class="ordinary" @click="handlesh(row)"
              v-limit="'KJSL:KJJL:YXKJTD:EXAMINE'">审核</el-button>
          </div>
          <div v-if="row.status == '正常办结'">
            <el-button size="small" class="ordinary" @click="handlecx(row)"
              v-limit="'KJSL:KJJL:YXKJTD:REVOKE'">撤销</el-button>
          </div>
          <div v-if="row.status == '已驳回'">
            <el-button size="small" class="ordinary" @click="handleEdit(row)"
              v-limit="'KJSL:KJJL:YXKJTD:EDIT'">编辑</el-button>
            <el-button size="small" class="ordinary" @click="handletj(row)"
              v-limit="'KJSL:KJJL:YXKJTD:SUBMIT'">提交</el-button>
          </div>
        </template>
      </Table>
    </div>

    <el-dialog v-model="data.dialogVisible" width="900px" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header" v-loading="data.detail_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="流程图" name="four" v-if="data.status == 1">
              <flowChart :processInstanceId="data.processInstanceId"></flowChart>
            </el-tab-pane>

            <el-tab-pane label="基本信息" name="first">
              <Information v-if="data.dialogVisible" @valueFlag="valueFlag" ref="getAssociation"
                :orgAllList="data.orgAllList"></Information>
            </el-tab-pane>
            <el-tab-pane label="附件信息" name="second">
              <platformFiles :files="data.fileList" @dataChange="dataChange" download="KJSL:KJJL:YXKJTD:DOWNLOAD"
                upload="KJSL:KJJL:YXKJTD:UPLOAD" fileDelete="KJSL:KJJL:YXKJTD:FILEDELETE"></platformFiles>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <template #footer>
        <div class="dialog-footer" style="float:left" v-if="data.status == 1">
          <el-form  :rules="rules" ref="ruleFormRef" :model="ruleForm">
            <el-form-item label="审批意见" prop="comment">
              <el-input
                :rows="2"
                 type="textarea"
                  placeholder="审批意见"
                  v-model="ruleForm.comment"
                  style="width: 450px"
                  clearable
                />
            </el-form-item>
          </el-form>
        </div>

        <div class="dialog-footer" v-if="data.status == 0">
          <el-button @click="data.dialogVisible = false">关闭</el-button>
          <!-- <el-button type="primary">下载</el-button>
          <el-button type="primary">暂存</el-button> -->
          <el-button type="primary" @click="sure">保存</el-button>
        </div>
        <div class="dialog-footer" v-if="data.status == 1" style="margin-top:20px">
          <el-button @click="closeVisable">关闭</el-button>
          <el-button type="primary" @click="handlebh">驳回</el-button>
          <el-button type="primary" @click="handletg">通过</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="data.dealVisible" title="系统正在处理中....." width="40%" top="14%" height="400" :show-close="false"
      :close-on-click-modal="false">
      <el-alert type="success" :closable="false" style="margin-bottom:20px" description="当前流程正在处理中,请稍等……">
      </el-alert>
    </el-dialog>

  </div>
</template>
<script lang="js">
import flowChart from '@/components/PublicProcess/Chart/flowChart.vue'
import * as proxy from "@/constants/proxy"
import request from "@/utils/request"
import Api from '@/views/science/api/group'
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import { computed, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import Information from './information.vue'

export default {
  components: {
    SelectOption,
    Table,
    platformFiles,//附件
    Information,//基本信息
    flowChart
  },
  setup() {

    onMounted(() => {
      getOrgList();
    });
    const store = useStore()
    const activeName = ref('first')//tab切换

    const ruleForm = reactive({
      comment: '',
    })

    const rules = reactive({
      comment: [
        { required: true, message: '请输入审核意见', trigger: 'change', },
      ]
    })

    const ruleFormRef = ref()
    let data = reactive({
      isLoading: false,
      detail_loading: false,
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true,
      },

      orgAllList: [],
      dealVisible: false,
      businessKey: '',
      times: null,
      processInstanceId: '',
      flag: null,
      status: 0, //0编辑，1审核
      dialogVisible: false,//弹窗
      page: { page: 1, limit: 10, total: 0 },
      ids: [],
      searchParams: {
        page: 1,
        pageSize: 10,
        teamName: "",
        recommendUnit: ""
      },
      allTableData: [],
      columns: [
        {
          key: 'teamName',
          width: 140,
          label: '团队名称',
        },
        {
          key: 'recommendUnit',
          width: 140,
          label: '推荐单位',
        },
        {
          key: 'teamCharge',
          width: 140,
          label: '团队负责人',
        },
        {
          key: 'unitContact',
          width: 140,
          label: '单位联系人',
        },
        {
          key: 'unitContactRel',
          width: 140,
          label: '联系电话',
        },
        {
          key: 'unitContactEmail',
          width: 140,
          label: '电子邮箱',
        },
        {
          key: 'mainCompletePersons',
          width: 140,
          label: '团队成员',
        },
        {
          key: 'status',
          width: 140,
          label: '状态',
          textColor: true
        },
      ],
      participantlist: [], //附表信息
      fileList: [], //附件信息
    })
    const loading = ref(true)//加载
    // 存储下拉框数组的对象
    const options = reactive({
      unitList: computed(() => store.state.technologyStrength.orgAllList),
    })

    const getListData = () => { // 获取列表数据
      loading.value = true   // 加载
      data.isLoading = true
      Api.getTotalList(data.searchParams)
        .then((res) => { // 获取列表数据
          console.log('获取数据列表', res.data.data) // 获取列表数据
          let resData = res.data.data // 获取列表数据
          resData.records.map((item) => {
            if (item.status == 0) {
              item.status = "待提交"
            } else if (item.status == 1) {
              item.status = "办理中"
            } else if (item.status == 2) {
              item.status = "正常办结"
            } else if (item.status == 3) {
              item.status = "已退回"
            }
            else if (item.status == 4) {
              item.status = "已撤办"
            }
            else if (item.status == 5) {
              item.status = "强制办结"
            }
            else if (item.status == 6) {
              item.status = "已废弃"
            }
            else if (item.status == 7) {
              item.status = "已挂起"
            }
            else if (item.status == 8) {
              item.status = "已驳回"
            }
          })
          data.allTableData = resData.records   // 获取列表数据
          data.page.total = resData.total   // 获取列表数据
          data.isLoading = false
        })
        .finally(() => { // 获取列表数据
          loading.value = false  // 获取列表数据
        }).catch((error) => {
          data.isLoading = false
        })
    }

    //详情数据获取
    const detailData = async (id) => {
      data.detail_loading = true
      data.dialogVisible = true

      Api.detailData({
        id: id
      })
        .then((res) => { // 获取列表数据
          store.commit('technologyStrength/getgroupINFO', { ...res.data.data.baseInfo })
          data.processInstanceId = res.data.data.baseInfo.processInstanceId
          data.fileList = res.data.data.fileList
          data.detail_loading = false
          // data.addFlag = 1
        }).catch((error) => {
          data.detail_loading = false
        })
    }

    const changeValue = (item) => {
      console.log('item,', item);
      data.searchParams.recommendUnit = item.name
      // data.searchParams.recommendUnitId = item.id
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      getListData()
    }

    let changeUnit = (val) => {
      if (val == null) {
        data.searchParams.recommendUnit = ''
        return false
      }
      if (val.length > 0) {
        let unitId = val[val.length - 1]
        data.searchParams.recommendUnit = unitId
      }
    }



    let getOrgList = () => {
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res => {
        data.orgAllList = res.data.data
      })
    }

    // 删除
    let deleteList = () => { // 删除
      if (data.ids.length) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let list = []
          data.allTableData.forEach(e => {
            if (data.ids.includes(e.id)) {
              list.push(e.status)
            }
          })
          if (list.includes('办理中') || list.includes('正常办结') || list.includes('已退回') || list.includes('已撤办') || list.includes('强制办结') || list.includes('已废弃') || list.includes('已挂起')) {
            tips('只允许删除待提交和已驳回状态的数据', 'warning')
          } else {
            let res = await Api.deleteList({
              id: data.ids + ''
            })
            if (res.data.success) {
              tips('删除成功', 'success')
              getListData()
            }
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }

    const getExport = () => {//导出
      let msg = '是否导出全部数据'
      if (data.ids.length > 0) {
        msg = '是否导出所选数据'
      }
      Modals(msg, '提示', 'warning').then(async () => {
        const params = {
          ...data.searchParams,
          ids: data.ids
        }
        await Api.export(params, "优秀科技团队")
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const valueFlag = (flag) => {
      data.flag = flag
    }

    const dataChange = (params) => {//附件
      data.fileList = params
    }

    const delectIds = (ids) => {
      data.ids = ids
    }

    const currentChange = (current) => {
      data.searchParams.page = current
      getListData()
    }

    //修改
    const handleEdit = (row) => {
      store.commit('technologyStrength/getRowId', row.id)
      detailData(row.id)
      data.status = 0
    }

    let handletj = (row) => {

      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await Api.startProcess({
            flowKey: 'excellent_team1',
            businessKey: row.id,
            businessType: 'YW03',
            random: (new Date()).valueOf()
          });


          if (res.data.code == 200) {

            data.dealVisible = true

            deal(row.id, 1)

          } else {

            tips(res.data.message, 'warning')

          }

        })
        .catch(() => { });

    }



    let deal = (id, state) => {

      data.times = setInterval(() => {

        Api.detailData({
          id: id
        })
          .then((res) => {

            const resData = res.data.data

            if (resData.baseInfo.status == state) {

              data.dealVisible = false

              getListData()


              clearTimeout(data.times)

            }

          })

      }, 1000);

    }

    //审核
    const handlesh = (row) => {
      store.commit('technologyStrength/getRowId', row.id)

      data.businessKey = row.id
      data.status = 1
      activeName.value = 'four'
      detailData(row.id)
    }

    //驳回
    const handlebh = () => {

      ruleFormRef.value.validate(valid => {
        if (valid) {

          Modals('是否驳回本次内容', '提示', 'warning').then(async () => {
            let res = await Api.refuseProcess({
              procInsId: data.processInstanceId,
              comment: ruleForm.comment,
              businessKey: data.businessKey,
              businessType: 'YW03',
              random: (new Date()).valueOf()
            })

            if (res.data.code == 200) {

              ruleForm.comment = ''

              data.dialogVisible = false

              data.dealVisible = true

              deal(data.businessKey, 8)

            } else {

              tips(res.data.data.message, 'warning')

            }

          }).catch(() => {
            console.log("点击了取消")
          })

        }
      })
    }

    //通过
    const handletg = () => {

      ruleFormRef.value.validate(valid => {
        if (valid) {

          Modals('是否通过本次内容', '提示', 'warning').then(async () => {
            let res = await Api.allowProcess({
              procInsId: data.processInstanceId,
              comment: ruleForm.comment,
              businessKey: data.businessKey,
              businessType: 'YW03',
              random: (new Date()).valueOf()
            })


            if (res.data.code == 200) {

              data.dialogVisible = false

              ruleForm.comment = ''

              data.dealVisible = true

              dealCheck(data.businessKey)



            } else {

              tips(res.data.message, 'warning')

            }


          }).catch(() => {
            console.log("点击了取消")
          })

        }
      })

      // 处理通过的过程中.......

    }

    let dealCheck = (id) => {


      data.times = setInterval(() => {

        Api.detailData({
          id: id
        })
          .then((res) => {

            let resData = res.data.data

            if (resData.baseInfo.status == 2) {


              data.dealVisible = false


              getListData()


              clearTimeout(data.times)

            }

            if (resData.baseInfo.status == 1 && resData.baseInfo.currTaskTd !== data.taskId) {


              data.dealVisible = false


              getListData()


              clearTimeout(data.times)

            }

          })

      }, 1000);
    }

    //撤销
    const handlecx = (row) => {
      Modals('是否撤销审核通过的内容', '提示', 'warning').then(async () => {
        let res = await Api.rollback({
          id: row.id
        })
        if (res.data.success) {
          tips('撤销成功', 'success')
          getListData()
        }
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const closeVisable = () => {
      ruleFormRef.value.resetFields();
      data.dialogVisible = false

    }

    const add = () => {//新增
      console.log('ruleFormRef', ruleFormRef.value);
      data.dialogVisible = true //弹窗
      data.status = 0
      // ruleFormRef.value.resetFields();
      store.commit('technologyStrength/emptygroupINFO')
    }

    const getAssociation = ref()

    const sure = async () => { // 确定
      const form = store.state.technologyStrength.groupINFO
      getAssociation.value.submitForm()

      if (!data.flag) {
        return tips('请将基本信息补充完整', 'warning')
      }
      const params = {
        baseInfo: form,
        fileList: data.fileList
      }
      let res
      if (form.id) {
        res = await Api.update(params)
      } else {
        res = await Api.insert(params)
      }

      if (res.data) {
        tips('保存成功', 'success')
        store.commit('technologyStrength/emptygroupINFO')
        getListData()  // 获取列表数据
        data.dialogVisible = false  // 弹窗
      }

    }


    getListData()
    return {
      closeVisable,
      search,
      getAssociation,
      dataChange,
      delectIds,
      currentChange,
      changeValue,
      deal,

      activeName,
      options,
      data,

      handleEdit,
      handletj,
      handlesh,
      handlecx,
      handlebh,
      handletg,

      // 列表
      valueFlag,
      getListData,
      // 新增
      add,
      sure,
      ruleForm,
      rules,
      ruleFormRef,
      dealCheck,
      changeUnit,

      deleteList,
      getExport,
      getOrgList
    }
  },
}
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}

.el-col {
  line-height: 40px;
}

.el-form-item {
  .el-input {
    width: 100px;
    background-color: aliceblue;
  }

  .el-select {
    width: 100px;
  }
}

.custom-color {
  color: red !important;
  /* 确保优先级高于其他样式 */
}

.el-table th {
  background-color: #f0f0f0;
  /* 修改表头背景色 */
  color: #333;
  /* 修改表头文字颜色 */
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */

.open-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
}

/deep/.el-dialog__body {
  display: block !important;
}

.mt15 {
  margin-top: 15px;
}

.mb10 {
  margin-bottom: 10px;
}

.tc {
  text-align: center;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}
</style>

<style lang="scss" >
.conUnitName {
  display: inline-block;
  width: 200px;
}

.gy-cascader {
  .el-cascader-node {
    max-width: 250px;
  }
}
</style>

